***************************************************************************************************************
* Name: Table A4 alternative entry 25th percentile
* Description: Strategic coefficients in output are pP and pF
* Reference: "Competition and Civilian Victimization"
***************************************************************************************************************

use "violence_t_export.dta",clear
keep if victim_farc3~=.&victim_paras3~=.

*****Log likelihood definition*****

global vF "victim_farc3"
global vP "victim_paras3" 

*Victimization un-restricted
capture program drop lfsec_ur
program lfsec_ur
  version 13.1
  args lnf xbF xbP
  tempvar pF pP
  quietly {
     gen double `pF' = 1/(1+exp(-`xbF'))
     gen double `pP' = 1/(1+exp(-`xbP'))
     replace `lnf' = $vP* ln(`pP')+(1-$vP)*ln(1-`pP') + $vF*ln(`pF')+(1-$vF)*ln(1-`pF') 
   }
end


*Two stage estimation
 capture program drop game2stage
 program game2stage, eclass
	syntax [if]
	marksample touse
	tempname b b2 dF2 dP2
	tempvar predF predP
	local controls "nbi_t royalties_t coca_t share_left lpobl_tot_t i.time army_dist gini_i dmr evlp gcaribe gpacifica gorinoquia gamazonia"
	
	quietly {
		npregress kernel victim_farc3 `controls' farc_dist if victim_paras3~=., estimator(constant) noderivatives
		predict `predF'
		npregress kernel victim_paras3 `controls' paras_dist if victim_paras3~=.,estimator(constant) noderivatives
		predict `predP'
	}
	
	gen pF=`predF'
	gen pP=`predP'
		
	corr  pF victim_farc3 pP victim_paras3
	ml model lf lfsec_ur (eq1: victim_farc3 = nbi_t royalties_t coca_t share_left lpobl_tot_t army_dist  ///
						 dmr gini_i  time evlp gcaribe gpacifica gorinoquia gamazonia farc_dist pP) (eq2: nbi_t royalties_t coca_t ///
						share_left lpobl_tot_t army_dist dmr gini_i time ///
						 evlp  gcaribe gpacifica gorinoquia gamazonia paras_dist pF)
	capture noisily ml maximize, diff 
	display "maximize" _rc
	if _rc~=0 {
		matrix `b2'=J(1,34,0)
		matrix `dF2'=J(1,13,0)
		matrix `dP2'=J(1,13,0)	
	}
	else{
		matrix `b2'=e(b)

		quietly{
			margins , at(pP=(0.2(0.05)0.8) time=2 gcaribe=0 gpacifica=0 gorinoquia=0 gamazonia=0 ) atmeans expression(exp(predict(equation(eq1)))/(1+exp(predict(equation(eq1))))) nose
			matrix `dF2'=r(b)

			margins , at(pF=(0.2(0.05)0.8) time=2 gcaribe=0 gpacifica=0 gorinoquia=0 gamazonia=0 ) atmeans expression(exp(predict(equation(eq2)))/(1+exp(predict(equation(eq2))))) nose
			matrix `dP2'=r(b)
			}
	}		
	matrix `b'=(`b2',`dF2',`dP2')		
		
	*drop pF pP
	ereturn post `b' ,esample(`touse')		
	
end

game2stage

